package cn.appsys.controller.developer;

import cn.appsys.pojo.*;
import cn.appsys.service.developer.AppCategoryService;
import cn.appsys.service.developer.AppInfoService;
import cn.appsys.service.developer.AppVersionService;
import cn.appsys.service.developer.DataDictionaryService;
import cn.appsys.util.PageSupport;
import com.alibaba.fastjson.JSON;
import com.mysql.jdbc.StringUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("/dev/platform")
public class AppController {

    @Autowired
    private AppInfoService appInfoService;

    @Autowired
    private AppCategoryService appCategoryService;

    @Autowired
    private DataDictionaryService dataDictionaryService;

    @Autowired
    private AppVersionService appVersionService;

    //分页查询
    @RequestMapping("/appList")
    public String appList(@RequestParam Map<String,Object> params, Model model){
        List<DataDictionary> statusList = dataDictionaryService.getDataDictionaryList("APP_STATUS");
        List<DataDictionary> flatFormList = dataDictionaryService.getDataDictionaryList("APP_FLATFORM");
        List<AppCategory> categoryLevel1List = appCategoryService.getAppCategoryListByParentId(null);

        String pageIndex=(String) params.get("pageIndex");
        if (StringUtils.isNullOrEmpty(pageIndex)){
            params.put("currentPageNo",1);
        }else {
            params.put("currentPageNo",Integer.parseInt(pageIndex));
        }
        params.put("pageSize",5);
        params.put("softwareName",params.get("querySoftwareName"));
        params.put("status",params.get("queryStatus"));
        params.put("flatformId",params.get("queryFlatformId"));
        params.put("categoryLevel1",params.get("queryCategoryLevel1"));
        params.put("categoryLevel2",params.get("queryCategoryLevel2"));
        params.put("categoryLevel3",params.get("queryCategoryLevel3"));

        PageSupport<AppInfo> pageSupport = appInfoService.getPageSupport(params);
        model.addAttribute("pages",pageSupport);
        model.addAttribute("categoryLevel1List",categoryLevel1List);
        model.addAttribute("flatFormList",flatFormList);
        model.addAttribute("statusList",statusList);
        model.addAttribute("querySoftwareName",params.get("querySoftwareName"));
        model.addAttribute("queryStatus",params.get("queryStatus"));
        model.addAttribute("queryFlatformId",params.get("queryFlatformId"));
        model.addAttribute("queryCategoryLevel1",params.get("queryCategoryLevel1"));
        model.addAttribute("queryCategoryLevel2",params.get("queryCategoryLevel2"));
        model.addAttribute("queryCategoryLevel3",params.get("queryCategoryLevel3"));

        if (!StringUtils.isNullOrEmpty((String) params.get("queryCategoryLevel2"))){
            Integer pid=Integer.parseInt(params.get("queryCategoryLevel1").toString());
            List<AppCategory> categoryLevel2List = appCategoryService.getAppCategoryListByParentId(pid);
            model.addAttribute("categoryLevel2List",categoryLevel2List);
        }
        if (!StringUtils.isNullOrEmpty((String) params.get("queryCategoryLevel3"))){
            Integer pid=Integer.parseInt(params.get("queryCategoryLevel2").toString());
            List<AppCategory> categoryLevel3List = appCategoryService.getAppCategoryListByParentId(pid);
            model.addAttribute("categoryLevel3List",categoryLevel3List);
        }

        return "developer/appinfolist";
    }

    //ajax加载一、二、三分类
    @RequestMapping(value = "/categorylevellist",produces = "application/json;charset=utf-8",method = RequestMethod.GET)
    @ResponseBody
    public Object categorylevellist(String pid){

        List<AppCategory> appCategoryListByParentId
                = appCategoryService.getAppCategoryListByParentId(pid.equals("")?null:Integer.parseInt(pid));

        return JSON.toJSONString(appCategoryListByParentId);
    }

    //跳转appversion新增页面
    @RequestMapping("/appversionadd")
    public String appversionadd(Integer id, Model model, AppVersion appVersion, String error) {
        appVersion.setAppId(id);
        List<AppVersion> appVersionList = appVersionService.getAppVersionList(id);
        model.addAttribute("appVersionList",appVersionList);
        model.addAttribute(appVersion);
        model.addAttribute("fileUploadError",error);
        return "developer/appversionadd";
    }

    //增加appversion数据
    @RequestMapping("/addversionsave")
    public String addversionsave(HttpServletRequest request, HttpSession session,
                                 MultipartFile a_downloadLink, AppVersion appVersion, RedirectAttributes attr) {
        String path=session.getServletContext().getRealPath("statics"+ File.separator+"uploadFiles");
        File pathFile=new File(path);
        if (!pathFile.exists()){
            pathFile.mkdir();
        }
        String fileUploadError="";
        String oldFileName=a_downloadLink.getOriginalFilename();
        String fileName="";
        String apkName="";
        if (!StringUtils.isNullOrEmpty(oldFileName)){
            if (a_downloadLink.getSize()>1024*1024*500){
                fileUploadError=" * 上传文件过大！";
            }else {
                String prefix= FilenameUtils.getExtension(oldFileName);
                if (!prefix.equals("apk")){
                    fileUploadError=" * 上传文件格式不正确！";
                }else {
                    apkName=appInfoService.getAppInfo(appVersion.getAppId()).getAPKName();

                    fileName= apkName+"-"+appVersion.getVersionNo()+"."+prefix;
                    File file=new File(path,fileName);
                    if (!file.exists()){
                        file.mkdir();
                    }
                    try {
                        a_downloadLink.transferTo(file);
                    } catch (IOException e) {
                        e.printStackTrace();
                        fileUploadError="* 上传失败！";
                    }
                    appVersion.setCreationDate(new Date());
                    appVersion.setDownloadLink(request.getContextPath()+"/statics/uploadFiles/"+fileName);
                    appVersion.setCreatedBy(((DevUser)session.getAttribute("devUserSession")).getId());
                    appVersion.setApkLocPath(path+File.separator+fileName);
                    appVersion.setApkFileName(fileName);
                    if (appVersionService.addAppVersion(appVersion)){
                        return "redirect:/dev/platform/appList";
                    }
                }
            }
        }else {
            fileUploadError="* 文件不能是空文件夹";
        }
        attr.addAttribute("id",appVersion.getAppId());
        attr.addAttribute("error",fileUploadError);
        return "redirect:/dev/platform/appversionadd";
    }

    //跳转appversion修改页面
    @RequestMapping("/appversionmodify")
    public String appversionmodify(Integer aid,Model model,Integer vid,String error){
        List<AppVersion> appVersionList = appVersionService.getAppVersionList(aid);
        AppVersion appVersion = appVersionService.getAppVersionById(vid);
        model.addAttribute(appVersion);
        model.addAttribute("fileUploadError",error);
        model.addAttribute("appVersionList",appVersionList);
        return "developer/appversionmodify";
    }

    //修改appversion数据
    @RequestMapping("/appversionmodifysave")
    public String appversionmodifysave(HttpServletRequest request, HttpSession session,
                                       MultipartFile attach, AppVersion appVersion, RedirectAttributes attr){
        String path=session.getServletContext().getRealPath("statics"+ File.separator+"uploadFiles");
        File pathFile=new File(path);
        if (!pathFile.exists()){
            pathFile.mkdir();
        }
        String fileUploadError="";
        String oldFileName=attach.getOriginalFilename();
        String fileName="";
        String apkName="";
        if (!StringUtils.isNullOrEmpty(oldFileName)){
            if (attach.getSize()>1024*1024*500){
                fileUploadError=" * 上传文件过大！";
                attr.addAttribute("vid",appVersion.getId());
                attr.addAttribute("aid",appVersion.getAppId());
                attr.addAttribute("error",fileUploadError);
                return "redirect:/dev/platform/appversionmodify";
            }else {
                String prefix= FilenameUtils.getExtension(oldFileName);
                if (!prefix.equals("apk")){
                    fileUploadError=" * 上传文件格式不正确！";
                    attr.addAttribute("vid",appVersion.getId());
                    attr.addAttribute("aid",appVersion.getAppId());
                    attr.addAttribute("error",fileUploadError);
                    return "redirect:/dev/platform/appversionmodify";
                }else {
                    apkName=appInfoService.getAppInfo(appVersion.getAppId()).getAPKName();

                    fileName= apkName+"-"+appVersion.getVersionNo()+"."+prefix;
                    File file=new File(path,fileName);
                    if (!file.exists()){
                        file.mkdir();
                    }
                    try {
                        attach.transferTo(file);
                    } catch (IOException e) {
                        e.printStackTrace();
                        fileUploadError="* 上传失败！";
                        attr.addAttribute("vid",appVersion.getId());
                        attr.addAttribute("aid",appVersion.getAppId());
                        attr.addAttribute("error",fileUploadError);
                        return "redirect:/dev/platform/appversionmodify";
                    }
                    appVersion.setDownloadLink(request.getContextPath()+"/statics/uploadFiles/"+fileName);
                    appVersion.setApkLocPath(path+File.separator+fileName);
                    appVersion.setApkFileName(fileName);
                }
            }
        }else {
            appVersion.setDownloadLink(null);
            appVersion.setApkLocPath(null);
            appVersion.setApkFileName(null);
        }
        appVersion.setModifyDate(new Date());
        appVersion.setModifyBy(((DevUser)session.getAttribute("devUserSession")).getId());
        if (appVersionService.updateAppVersion(appVersion)){
            return "redirect:/dev/platform/appList";
        }
        return "redirect:/dev/platform/appversionmodify";
    }

    //删除apk文件或者logo图片
    @RequestMapping(value = "/delfile",produces = "application/json;charset=utf-8")
    @ResponseBody
    public Object delfile(Integer id,String flag){
        Map<String,Object> map=new HashMap<>();
        if (flag.equals("apk")){
            AppVersion version = appVersionService.getAppVersionById(id);
            String apkLocPath = version.getApkLocPath();
            File file=new File(apkLocPath);
            if (file.exists()){
                if (file.delete()){
                    if (appVersionService.deleteApkFile(id)){
                        map.put("result","success");
                    }
                }
            }
        }else if (flag.equals("logo")){
            AppInfo appInfo = appInfoService.getAppInfo(id);
            String logoLocPath = appInfo.getLogoLocPath();
            File file=new File(logoLocPath);
            if (file.exists()){
                if (file.delete()){
                    if (appInfoService.deleteAppLogo(id)){
                        map.put("result","success");
                    }
                }
            }
        }
        return JSON.toJSONString(map);
    }

    //跳转app修改页面
    @RequestMapping("/appinfomodify")
    public String appinfomodify(Integer id,Model model,String error){
        AppInfo appInfo = appInfoService.getAppInfo(id);
        model.addAttribute(appInfo);
        model.addAttribute("fileUploadError",error);
        return "developer/appinfomodify";
    }

    //ajax加载所属平台
    @RequestMapping(value = "/datadictionarylist",produces = "application/json;charset=utf-8")
    @ResponseBody
    public Object datadictionarylist(String typeCode){
        List<DataDictionary> dataDictionaryList = dataDictionaryService.getDataDictionaryList(typeCode);
        return JSON.toJSONString(dataDictionaryList);
    }

    //修改app数据
    @RequestMapping("/appinfomodifysave")
    public String appinfomodifysave(HttpServletRequest request, HttpSession session,
                                    MultipartFile attach, AppInfo appInfo, RedirectAttributes attr){
        String oldFileName=attach.getOriginalFilename();
        if (!StringUtils.isNullOrEmpty(oldFileName)){
            String path=session.getServletContext().getRealPath("statics"+ File.separator+"uploadFiles");
            if (attach.getSize()>1024*500){
                attr.addAttribute("id",appInfo.getId());
                attr.addAttribute("error"," * 上传文件过大！");
                return "redirect:/dev/platform/appinfomodify";
            }else {
                String prefix= FilenameUtils.getExtension(oldFileName);
                if (prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
                        ||prefix.equalsIgnoreCase("jepg") || prefix.equalsIgnoreCase("pneg")){
                    String apkName=appInfo.getAPKName();
                    String fileName=apkName+"."+prefix;
                    File file=new File(path,fileName);
                    if (!file.exists()){
                        file.mkdir();
                    }
                    try {
                        attach.transferTo(file);
                    } catch (IOException e) {
                        attr.addAttribute("id",appInfo.getId());
                        attr.addAttribute("error","* 上传失败！");
                        return "redirect:/dev/platform/appinfomodify";
                    }
                    appInfo.setLogoLocPath(path+File.separator+fileName);
                    appInfo.setLogoPicPath(request.getContextPath()+"/statics/uploadFiles/"+fileName);
                }else {
                    attr.addAttribute("id",appInfo.getId());
                    attr.addAttribute("error","* 上传文件格式不正确！");
                    return "redirect:/dev/platform/appinfomodify";
                }
            }
        }else {
            appInfo.setLogoLocPath(null);
            appInfo.setLogoPicPath(null);
        }
        appInfo.setModifyBy(((DevUser)session.getAttribute("devUserSession")).getId());
        appInfo.setModifyDate(new Date());
        if (appInfoService.updateAppInfo(appInfo)){
            return "redirect:/dev/platform/appList";
        }
        attr.addAttribute("id",appInfo.getId());
        return "redirect:/dev/platform/appinfomodify";
    }

    //跳转app查询页面
    @RequestMapping("/appview/{id}")
    public String appview(@PathVariable Integer id,Model model){
        AppInfo appInfo = appInfoService.getAppInfo(id);
        List<AppVersion> appVersionList = appVersionService.getAppVersionList(id);
        model.addAttribute(appInfo);
        model.addAttribute("appVersionList",appVersionList);
        return "developer/appinfoview";
    }

    //跳转app增加页面
    @RequestMapping("/appinfoadd")
    public String appinfoadd(){
        return "developer/appinfoadd";
    }

    //上传app增加数据
    @RequestMapping("/appinfoaddsave")
    public String appinfoaddsave(AppInfo appInfo,HttpSession session,MultipartFile a_logoPicPath,HttpServletRequest request){
        String path=session.getServletContext().getRealPath("statics"+ File.separator+"uploadFiles");
        File pathFile=new File(path);
        if (!pathFile.exists()){
            pathFile.mkdir();
        }
        String fileUploadError="";
        String oldFileName=a_logoPicPath.getOriginalFilename();
        if (!StringUtils.isNullOrEmpty(oldFileName)){
            if (a_logoPicPath.getSize()>1024*500){
                fileUploadError=" * 上传文件过大！";
            }else {
                String prefix= FilenameUtils.getExtension(oldFileName);
                if (prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
                        ||prefix.equalsIgnoreCase("jepg") || prefix.equalsIgnoreCase("pneg")){
                    String fileName = appInfo.getAPKName() + ".jpg";
                    File targetFile = new File(path,fileName);
                    if(!targetFile.exists()){
                        targetFile.mkdirs();
                    }
                    try {
                        a_logoPicPath.transferTo(targetFile);
                    } catch (IOException e) {
                        e.printStackTrace();
                        fileUploadError=" * 上传失败！";
                    }
                    appInfo.setLogoLocPath(path+File.separator+fileName);
                    appInfo.setLogoPicPath(request.getContextPath()+"/statics/uploadFiles/"+fileName);
                    appInfo.setCreatedBy(((DevUser)session.getAttribute("devUserSession")).getId());
                    appInfo.setCreationDate(new Date());
                    appInfo.setStatus(1);
                    appInfo.setDevId(((DevUser)session.getAttribute("devUserSession")).getId());
                    if (appInfoService.addAppInfo(appInfo)){
                        return "redirect:/dev/platform/appList";
                    }

                }else {
                    fileUploadError=" * 上传文件格式不正确！";
                }
            }
        }
        request.setAttribute("fileUploadError",fileUploadError);
        return "developer/appinfoadd";
    }

    //判断apkName是否是唯一
    @RequestMapping(value = "/apkexist",produces = "application/json;charset=utf-8")
    @ResponseBody
    public Object apkexist(String APKName){
        HashMap<String, String> resultMap = new HashMap<String, String>();
        if (StringUtils.isNullOrEmpty(APKName)){
            resultMap.put("APKName","empty");
        }else {
            if (null==appInfoService.getAppInfoByName(APKName)){
                resultMap.put("APKName","noexist");
            }else {
                resultMap.put("APKName","exist");
            }
        }
        return JSON.toJSONString(resultMap);
    }

    //删除app和所有app历史版本信息
    @RequestMapping(value = "/delapp",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String delapp(Integer id,Integer status){

        HashMap<String, String> resultMap = new HashMap<String, String>();
        if (StringUtils.isNullOrEmpty(id.toString())){
            resultMap.put("delResult","notexist");
        }else {
            if (status==5 || status==3){
                if (appInfoService.deleteApp(id)){
                    resultMap.put("delResult","true");
                }else {
                    resultMap.put("delResult","false");
                }
            }else {
                resultMap.put("delResult","error");
            }
        }
        return JSON.toJSONString(resultMap);
    }

    //上架、下架操作
    @RequestMapping(value = "/{appid}/sale",produces = "application/json;charset=utf-8")
    @ResponseBody
    public Object sale(@PathVariable Integer appid,HttpSession session){
        HashMap<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("errorCode","0");
        if (appid>0){
            DevUser devUser=(DevUser) session.getAttribute("devUserSession");
            AppInfo appInfo=new AppInfo();
            appInfo.setId(appid);
            appInfo.setModifyBy(devUser.getId());
            if (appInfoService.updateAppStatus(appInfo)){
                resultMap.put("resultMsg","success");
            }else {
                resultMap.put("resultMsg","failed");
            }
        }else {
            resultMap.put("errorCode","exception000001");
        }
        return JSON.toJSONString(resultMap);
    }

    public static void main(String[] args) {
        System.out.println();
    }
}
